package com.lwx.thread.product;

import java.util.ArrayList;
import java.util.List;

public class Storage {
    List<Object> list = new ArrayList<Object>();
    int maxSize = 10;
    
    public void produce(Object o) throws InterruptedException{
        synchronized (list) {
            while(list.size() >= maxSize){
                list.wait();
            }
            
            list.add(o);
            
            list.notify();
        }
    }
    
    public Object consume() throws InterruptedException{
        synchronized (list) {
            while(list.size() == 0){
                list.wait();
            }
            list.notify();
            return list.remove(0);
        }
    }
    
    public static void main(String[] args) {
        final Storage storage = new Storage();
        for(int i = 0; i < 100; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        storage.produce(1);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        
        for(int i = 0; i < 89; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println(storage.consume());
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }
}
